<script setup lang="ts">
import { DragDemonstration } from '@/utils/svg';
import { generateRandomId, QUESTION_TYPE_CONFIG, questionTypeList } from '@/views/exam/template/info/config';
import { DraggableEvent, VueDraggable } from 'vue-draggable-plus';
import {
  ExamAnswerMode,
  GenerateTemplateForm,
  QuestionType,
  TemplateForm,
  TemplateSchema
} from '@/api/exam/template/types';
import { TagTypeEnum, TagVO } from '@/api/exam/tag/types';
import VueJsonPretty from 'vue-json-pretty';
import 'vue-json-pretty/lib/styles.css';
import { addTemplate, genQuestion, getGenStatus } from '@/api/exam/template';
import { listTag } from '@/api/exam/tag';
import _ from 'lodash';
import { getAntTagColor } from '@/utils/tagColor';
import { listRepo, listRepoAndTemplate } from '@/api/exam/repo';
import { RepoInfoVo, RepoVO } from '@/api/exam/repo/types';
import { useSseStore } from '@/store/modules/sseStore';
import FileImport from '@/views/exam/template/fileImport.vue';
import TemplatePreview from './preview.vue';
import { ProjectForm } from '@/api/exam/project/types';
import { projectQuestionTypeStrategies } from '@/views/exam/project/info/config';
import { SegmentedOptions } from '@/types/type';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

interface Props {
  projectForm: any | ProjectForm;
}

const props = withDefaults(defineProps<Props>(), {
  projectForm: {
    survey: {
      children: []
    }
  }
});
const projectForm = ref<ProjectForm>(props.projectForm);
watch(() => props.projectForm, () => {
  projectForm.value = props.projectForm;
});

const view = ref('edit');

const viewOptions = [{
  label: '编辑',
  icon: 'edit',
  value: 'edit'
}, {
  label: 'Json',
  icon: 'json',
  value: 'json'
}, {
  label: '预览',
  icon: 'eye',
  value: 'preview'
}];
const setting = ref('base');
const isCurrentTemplate = ref(false);
const settingOptions = [{
  label: '全局设置',
  icon: 'setting',
  value: 'base'
}, {
  label: '题目设置',
  icon: 'question',
  value: 'template'
}, {
  label: '选项设置',
  icon: 'setting',
  value: 'option'
}];
const questionPanel = ref('questionType');
const questionPanelOptions: SegmentedOptions[] = [{
  label: '题型',
  icon: 'grid',
  value: 'questionType'
}, {
  label: '题库',
  icon: 'repo',
  value: 'repo'
}, {
  label: '大纲',
  icon: 'repo-dict',
  value: 'outline'
}];


const deepClone = <T>(obj: T): T => JSON.parse(JSON.stringify(obj));


const templateTagList = ref<TagVO[]>([]);
/*查询题目标签列表 */
const getTemplateTagList = async () => {
  const res = await listTag({ tagType: TagTypeEnum.TemplateType });
  templateTagList.value = res.data;
};


const { exam_question_type } = toRefs<any>(proxy?.useDict('exam_question_type'));
const currentTemplate = ref<TemplateSchema>();

const showQuestionDescription = ref(false);
const buttonLoading = ref(false);

/*当前选中题目*/
const hoverCurrentTemplateIndex = ref();
const activeQuestionIndex = ref(-1);
const handleClickQuestion = (index: any) => {
  activeQuestionIndex.value = index;
  setting.value = 'template';
};

// 拖拽组件自定义克隆
const handleClone = (original) => {
  return {
    ...deepClone(original.template) // 深拷贝核心模板
  };
};
// 拖拽结束处理
const handleDragAdd = (event: DraggableEvent) => {
  activeQuestionIndex.value = event.newIndex;
  handleQuestion(projectForm.value.survey.children[activeQuestionIndex.value]);
  nextTick(() => {
    const container = document.querySelector('.question-edit');
    const targetElement = container?.children[event.newIndex];
    targetElement?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
  });
};
// 点击克隆处理方法
const handleClickClone = (item: any) => {
  const clonedItem = handleClone(item);
  projectForm.value.survey.children.push(clonedItem);
  activeQuestionIndex.value = projectForm.value.survey.children.length - 1;
  handleQuestion(projectForm.value.survey.children[activeQuestionIndex.value]);
  nextTick(() => {
    const container = document.querySelector('.question-edit');
    const targetElement = container?.children[activeQuestionIndex.value];
    targetElement?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
  });
};

const importDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const handleDialogClose = (value) => {
  importDialog.visible = value;
  importDialog.title = '';
};
const importTemplate = (data) => {
  projectForm.value.survey.children = [...projectForm.value.survey.children, ...data];
  proxy?.$modal.notifySuccess('导入成功');
};
// 通过excel导入题目
const handleImport = () => {
  importDialog.visible = true;
  importDialog.title = '通过excel导入';
};

/*清空题目列表*/
const handleClear = () => {
  reset();
  getScoreTotal();
};


/*获取列表分值*/
const scoreTotal = ref(0);
const getScoreTotal = () => {
  scoreTotal.value = projectForm.value.survey.children.reduce((acc, item) => acc + item.attribute.examScore, 0);
  projectForm.value.survey.attribute.examScore = scoreTotal.value;
};
watch(() => projectForm.value.survey.children.length, () => {
  getScoreTotal();
});

const repoAndTemplateList = ref<RepoInfoVo[]>([]);
const getRepoAndTemplateList = async () => {
  const res = await listRepoAndTemplate();
  console.log(res.data);
  repoAndTemplateList.value = res.data;
};

const selectedRadioAnswerId = ref();
/*点击题目事件*/
const handleQuestion = (question: any) => {
  currentTemplate.value = question;
  /*如果是单选题或者是判断题，获取正确答案id*/
  if (currentTemplate.value.type === QuestionType.Radio || currentTemplate.value.type === QuestionType.TrueFalse) {
    currentTemplate.value.children.forEach((item: any) => {
      if (item.attribute?.examCorrectAnswer) {
        selectedRadioAnswerId.value = item.id;
      }
    });
  }
  /*获取是否显示题干说明*/
  if (currentTemplate.value.description === null || currentTemplate.value.description === undefined) {
    showQuestionDescription.value = false;
  } else {
    showQuestionDescription.value = true;
  }
  isCurrentTemplate.value = true;
  setting.value = 'template';
};
/*题干说明事件*/
const handleQuestionDescription = () => {
  if (showQuestionDescription.value) {
    currentTemplate.value.description = '';
  }
  if (!showQuestionDescription.value) {
    currentTemplate.value.description = null;
  }
};

/*复制题目*/
const copyQuestion = (index: number, question: any) => {
  const copiedQuestion = _.cloneDeep(question);
  copiedQuestion.id = generateRandomId();
  projectForm.value.survey.children.splice(index, 0, copiedQuestion);
};
/*移除题目*/
const removeQuestion = (index: any) => {
  projectForm.value.survey.children.splice(index, 1);
  isCurrentTemplate.value = false;
};
const addDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const addTemplateForm = ref<TemplateForm>();
const addRules = reactive({
  TemplateName: [{ required: true, message: '请输入题目', trigger: 'blur' }],
  repoId: [{ required: true, message: '请选择题库', trigger: 'change' }]
});
// 添加题目到指定题库
const addToRepo = (question: TemplateSchema) => {
  resetAdd();
  addTemplateForm.value.template = question;
  addDialog.visible = true;
};
const resetAdd = () => {
  addTemplateForm.value = undefined;
};
const repoList = ref<RepoVO[]>([]);
const addLoading = ref(false);
const submitAdd = async () => {
  addLoading.value = true;
  await addTemplate(addTemplateForm.value).finally(() => addLoading.value = false);
  proxy?.$modal.notifySuccess('添加成功');
  addDialog.visible = false;
};
const getRepoList = async () => {
  const res = await listRepo();
  repoList.value = res.data;
};

/*添加选项按钮*/
const addItem = (index: any) => {
  projectForm.value.survey.children[index].children.push({
    id: generateRandomId(), // 随机生成的id
    title: '',
    attribute: {
      examCorrectAnswer: undefined
    }
  });
};

/*移除选项*/
function remove(index: number, i: number) {
  projectForm.value[index].children.splice(i, 1);
}

const handleSettingAnswerMode = () => {
  const template = currentTemplate.value;
  const { examAnswerMode: mode, examScore } = template.attribute;
  const questionType = template.type;
  // 设置默认分数为 5 分
  const defaultScore = 5;

  const resetChildrenScores = () => {
    template.children.forEach(item => {
      item.attribute.examScore = null;
    });
  };
  const resetChildrenScoresAndCorrectAnswers = () => {
    template.children.forEach(item => {
      item.attribute.examScore = null;
      item.attribute.examCorrectAnswer = null; // 清除旧的正确答案标记
    });
  };

  // 设置子项属性，并可以选择是否同时设置默认分数
  const setChildAttributes = (setScore = true) => {
    template.children.forEach(item => {
      item.attribute.examCorrectAnswer = item.id; // 标记所有子项为正确答案
      if (setScore) {
        item.attribute.examScore = defaultScore; // 设置默认分数
      }
    });
  };

  // 计算总分
  const calculateTotalScore = () => {
    return template.children.reduce(
      (total, item) => total + (item.attribute.examScore || 0),
      0
    );
  };

  if (questionType === QuestionType.Radio) { // 单选题
    if (mode === ExamAnswerMode.onlyOne) { // 只选一个正确答案
      resetChildrenScoresAndCorrectAnswers(); // 重置所有子项的分数和正确答案标记
      template.children[0].attribute.examCorrectAnswer = template.children[0].id;
      template.children[0].attribute.examScore = defaultScore; // 设置第一个选项为正确答案并给予默认分数
    } else if (mode === ExamAnswerMode.select) { // 选择型
      resetChildrenScores(); // 重置旧的分数
      setChildAttributes(true); // 设置默认分数并标记所有子项为正确答案
    }
  } else if (questionType === QuestionType.Checkbox) { // 多选或填空题
    switch (mode) {
      case ExamAnswerMode.select:
        resetChildrenScores(); // 重置旧的分数
        setChildAttributes(true); // 设置默认分数并标记正确答案
        template.attribute.examScore = calculateTotalScore(); // 更新总分
        break;
      case ExamAnswerMode.selectCorrect:
        resetChildrenScores(); // 重置旧的分数
        template.children.forEach(item => {
          if (item.attribute.examCorrectAnswer) {
            item.attribute.examScore = defaultScore;
          }
        });// 设置有正确答案的选项的分值
        template.attribute.examScore = calculateTotalScore(); // 总分为 0，因为分数未设置
        break;
      case ExamAnswerMode.selectAll:
        resetChildrenScores(); // 清空所有分数和正确答案标记
        break;
    }
  } else if (questionType === QuestionType.MultipleBlank) {
    switch (mode) {
      case ExamAnswerMode.select:
        resetChildrenScores(); // 重置旧的分数
        template.children.forEach(item => {
          item.attribute.examScore = defaultScore; // 设置默认分数
        });
        template.attribute.examScore = calculateTotalScore(); // 更新总分
        break;
      case ExamAnswerMode.selectAll:
        resetChildrenScores(); // 重置旧的分数
        break;
    }
  }
  getScoreTotal();
};

// 计分方式选择事件
const handleQuestionMaxScore = (score: any) => {
  const template = currentTemplate.value;
  const { examAnswerMode } = template.attribute;
  const { type } = template;

  /* 合并最大值计算场景: 单选类题型 */
  if (
    examAnswerMode === 'onlyOne' ||
    examAnswerMode === 'selectAll' ||
    (type === 'Radio' && examAnswerMode === 'select')
  ) {
    template.attribute.examScore = Math.max(
      ...template.children.map((item: any) => item.attribute.examScore)
    );
  }

  /* 处理总和计算场景: 非单选类题型 */
  if (
    type !== 'Radio' &&
    (examAnswerMode === 'select' || examAnswerMode === 'selectCorrect')
  ) {
    template.attribute.examScore = template.children.reduce(
      (sum: number, item: any) => sum + item.attribute.examScore,
      0
    );
  }
  getScoreTotal();
};
/*单选题答案选择器事件*/
const handleRadioAnswer = () => {
  currentTemplate.value.children.forEach((item: any) => {
    item.attribute.examCorrectAnswer = null;
    if (item.id === selectedRadioAnswerId.value) {
      item.attribute.examCorrectAnswer = selectedRadioAnswerId.value;
    }
  });
};
/*题目类型选择事件*/
const handleSettingType = () => {
  if (currentTemplate.value.type === 'MultipleBlank') {
    let i = 1;
    currentTemplate.value.children.forEach((item: any) => {
      item.attribute.examCorrectAnswer = item.title;
      item.title = '填空' + i;
      i++;
    });
  }
  if (currentTemplate.value.type === 'Textarea') {
    currentTemplate.value.children = [{
      id: currentTemplate.value.children[0]['id'],
      title: '填空1',
      attribute: {
        examCorrectAnswer: currentTemplate.value.children[0]['attribute']['examCorrectAnswer']
      }
    }];
  }
  if (currentTemplate.value.type === 'TrueFalse') {
    currentTemplate.value.children = [{
      id: currentTemplate.value.children[0]['id'],
      title: '正确',
      attribute: {
        examCorrectAnswer: currentTemplate.value.children[0]['id']
      }
    }, {
      id: currentTemplate.value.children[1]['id'],
      title: '错误',
      attribute: {
        examCorrectAnswer: null
      }
    }];
  }
};
/*复制ID*/
const copyId = (id: any) => {
  try {
    navigator.clipboard.writeText(id);
    proxy?.$modal.notifySuccess('已复制ID');
  } catch (err) {
    proxy?.$modal.msgError('无法复制文本');
  }
};

/*json 展示*/
function formatToJsonObject(data: any) {
  try {
    let jsonList = [];
    data.forEach(item => {
      jsonList.push(item);
    });
    return jsonList;
  } catch (error) {
    return data;
  }
}

const reset = () => {
  view.value = 'edit';
  questionPanel.value = 'questionType';
  setting.value = 'base';
  currentTemplate.value = null;
  isCurrentTemplate.value = false;
  activeQuestionIndex.value = -1;
  hoverCurrentTemplateIndex.value = null;
  showQuestionDescription.value = false;
};
/** 关闭按钮 */
const cancel = () => {
  reset();
};

// 生成题目
const handleGen = async () => {
  dialog.visible = true;
};

interface QuestionGenRow {
  type: string;
  num: number;
}

const genForm = ref<GenerateTemplateForm>({
  requirements: '',
  children: []
});
const genLoading = ref(false);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
// 总题数计算
const totalNum = computed(() =>
  genForm.value.children.reduce((sum, row) => sum + (row.num || 0), 0)
);
// 获取当前行最大允许值
const getMaxAllowed = (row: QuestionGenRow) => {
  return 30 - (totalNum.value - row.num);
};
// 处理数量变化
const handleNumChange = (row: QuestionGenRow) => {
  if (totalNum.value > 30) {
    const maxAllowed = getMaxAllowed(row);
    row.num = maxAllowed;
    ElNotification({
      type: 'warning',
      title: '数量超限',
      message: `题目总数不能超过30，已自动调整为${maxAllowed}`,
      duration: 3000
    });
  }
};
const addGenRow = () => {
  if (totalNum.value >= 30) {
    ElNotification({
      type: 'warning',
      title: '操作限制',
      message: '题目总数已达上限，无法添加新题型',
      duration: 3000
    });
    return;
  }
  const item = { type: '单选题', num: 5 };
  genForm.value.children = [...genForm.value.children, item];
};
const removeGenRow = (index: any) => {
  genForm.value.children.splice(index, 1);
};
const sseStore = useSseStore();
const currentGenTaskId = ref('');
const submitGen = async () => {
  dialog.visible = false;
  const res = await genQuestion(genForm.value);
  dialog.visible = false;
  currentGenTaskId.value = res.msg;
  proxy?.$modal.notifyWait('正在生成题目...');
  genLoading.value = true;
};

const pollStatus = async () => {
  const res = await getGenStatus(currentGenTaskId.value);
  const temp = res.data.map(item => {
    return {
      ...item.template,
      id: item.templateId
    };
  });
  projectForm.value.survey.children = [...projectForm.value.survey.children, ...temp];
  getScoreTotal();
  genLoading.value = false;
};
watch(() => sseStore.sseData, (newValue) => {
  if (newValue === '题目生成结束') {
    pollStatus();
    sseStore.setSSEData(null);
  } else if (newValue === '题目生成错误') {
    genLoading.value = false;
    sseStore.setSSEData(null);
  }
});
const resetGen = () => {
  genForm.value = {
    requirements: '',
    children: []
  };
};

// 动态路径函数
const getDynamicValue = (item: any, questionType: QuestionType) => {
  const path = projectQuestionTypeStrategies[questionType]?.modelPath || '';
  return _.get(item, path);
};
const setDynamicValue = (item: any, questionType: QuestionType, val: string) => {
  const path = projectQuestionTypeStrategies[questionType]?.modelPath || '';
  // 创建新对象保证响应式更新
  const newItem = _.cloneDeep(item);
  _.set(newItem, path, val);
  // 保持对象引用不变的情况下更新属性
  Object.keys(newItem).forEach(key => {
    item[key] = newItem[key];
  });
};

defineExpose({
  reset, projectForm
});
onMounted(async () => {
  await getTemplateTagList();
  await getRepoAndTemplateList();
  await getRepoList();
  getScoreTotal();
});
</script>

<template>
  <el-aside class="sidebar-container drawer-left-menu"
            style="width: 300px !important;">
    <a-flex justify="center" class="segmented-style mb-2">
      <el-segmented v-model="questionPanel" :options="questionPanelOptions">
        <template #default="scope">
          <svg-icon :icon-class="scope.item['icon']" />
          <span class="ml-1">{{ scope.item['label'] }}</span>
        </template>
      </el-segmented>
    </a-flex>
    <div v-if="questionPanel === 'questionType'">
      <VueDraggable
        v-model="questionTypeList" :animation="150" ghostClass="ghost"
        :group="{ name: 'question', pull: 'clone', put: false }" :sort="false"
        :clone="handleClone" @start="activeQuestionIndex = -1"
        class="question-type flex w-100% rounded" handle=".handle"
      >
        <div v-for="item in questionTypeList" :key="item.questionType"
             @click="handleClickClone(item)"
             class="question-type-item handle cursor-move">
          <svg-icon class="mr-2" :icon-class="QUESTION_TYPE_CONFIG[item.questionType].icon" />
          <span>{{ QUESTION_TYPE_CONFIG[item.questionType].label }}</span>
        </div>
      </VueDraggable>
    </div>
    <div v-if="questionPanel==='repo'">
      <el-collapse>
        <el-collapse-item v-for="(repo,index) in repoAndTemplateList" :name="index"
                          :title="repo.repoName">
          <vue-draggable
            v-model="repo.children"
            :animation="150"
            ghostClass="ghost"
            :group="{ name: 'question', pull: 'clone', put: false }"
            :clone="handleClone" @start="activeQuestionIndex = -1"
            :sort="false" handle=".handle"
            class="question-type flex w-100%  rounded">
            <div v-for="(question, index) in repo.children" class="synopsis handle cursor-move"
                 @click="handleClickClone(question)">
              <div class="outline-icon">
                <svg-icon class="mr-1 " icon-class="drag-and-drop"></svg-icon>
              </div>
              <div v-if="index<9" class="outline-num">0{{ index + 1 }}</div>
              <div v-if="index>=9" class="outline-num">{{ index + 1 }}</div>
              <el-tooltip :content="question.templateName" placement="right-start">
                <el-text truncated style="width:  200px;">{{ question.templateName }}</el-text>
              </el-tooltip>
            </div>
          </vue-draggable>
        </el-collapse-item>
      </el-collapse>
    </div>
    <div v-if="questionPanel === 'outline' && projectForm">
      <VueDraggable
        v-model="projectForm.survey.children"
        :animation="300"
        :on-update="handleDragAdd"
        class="flex flex-col  m-auto"
        ghostClass="ghost"
        handle=".handle"
      >
        <div v-for="(question, index) in projectForm.survey.children" class="synopsis  handle cursor-move">
          <div class="outline-icon">
            <svg-icon class="handle cursor-move mr-1 " icon-class="drag-and-drop"></svg-icon>
          </div>
          <div v-if="index<9" class="outline-num">0{{ index + 1 }}</div>
          <div v-if="index>=9" class="outline-num">{{ index + 1 }}</div>
          <el-tooltip :content="question.title" placement="right-start">
            <el-text truncated style="width:  200px;">{{ question.title }}</el-text>
          </el-tooltip>
        </div>
        <a-empty class="empty-center" v-if="projectForm.survey.children.length===0" />
      </VueDraggable>
    </div>
  </el-aside>
  <el-container>
    <el-header height="50px" class="template-header">
      <div class="quick-setting">
        <el-text style="width: 70px" size="small" truncated align="center">总分{{ scoreTotal }}分</el-text>
        <el-tooltip content="清空">
          <a-button size="small" type="text" @click="handleClear()">
            <svg-icon icon-class="clear" />
          </a-button>
        </el-tooltip>
        <el-tooltip content="通过excel导入">
          <a-button size="small" type="text" @click="handleImport()">
            <svg-icon icon-class="excel" />
          </a-button>
        </el-tooltip>
        <el-tooltip content="生成题目">
          <a-button :loading="genLoading" size="small" type="text"
                    @click="handleGen">
            <svg-icon icon-class="generate" />
          </a-button>
        </el-tooltip>
      </div>
      <a-flex gap="middle">
        <div class="segmented-style">
          <el-segmented v-model="view" :options="viewOptions">
            <template #default="scope">
              <svg-icon :icon-class="scope.item['icon']" />
              <span class="ml-1">{{ scope.item['label'] }}</span>
            </template>
          </el-segmented>
        </div>
      </a-flex>

    </el-header>
    <el-main class="template-main">
      <a-card hoverable style="overflow-y: auto;overflow-x: clip;height: 100%">
        <div v-if="view==='edit' && projectForm">
          <VueDraggable
            v-model="projectForm.survey.children"
            :animation="300"
            class="question-edit flex flex-col  w-90% m-auto rounded"
            ghostClass="ghost"
            group="question"
            handle=".handle-item"
            :on-add="handleDragAdd"
          >
            <div v-for="(question, index) in projectForm.survey.children"
                 :class="{ 'hover-style': hoverCurrentTemplateIndex === index, 'clicked-style': activeQuestionIndex === index }"
                 @click="handleClickQuestion(index)" @mouseenter="hoverCurrentTemplateIndex = index"
                 @mouseleave="hoverCurrentTemplateIndex = null"
            >
              <!--右侧工具栏-->
              <div class="right-tool-bar">
                <el-tooltip content="复制" placement="right">
                  <a-button size="small" type="text" @click="copyQuestion(index,question)">
                    <svg-icon icon-class="copy" />
                  </a-button>
                </el-tooltip>
                <el-tooltip content="移除" placement="right">
                  <a-button size="small" type="text" @click="removeQuestion(index)">
                    <svg-icon icon-class="delete" color="#DC143C" />
                  </a-button>
                </el-tooltip>
                <el-tooltip content="添加到题库" placement="right">
                  <a-button size="small" type="text" @click="addToRepo(<TemplateSchema>question)">
                    <svg-icon icon-class="add" />
                  </a-button>
                </el-tooltip>
              </div>
              <div class="ml-50% mr-50%">
                <svg-icon style="font-size: 32px" class="handle-item cursor-move"
                          icon-class="drag-and-drop-transverse" />
              </div>
              <div class="p-4" @click="handleQuestion(question)">
                <div class="template-title">
                  <span><b>{{ index + 1 }}</b></span>
                  <a-input v-model:value="question.title" class="template-input" type="text" />
                  <span class="score">最高分值: {{ question.attribute.examScore }} 分</span>
                </div>
                <div v-show="question.description!==null"
                     class="template-description">
                  <input v-model="question.description" class="template-input"
                         type="text" placeholder="请输入题干说明" />
                </div>
                <VueDraggable
                  v-model="question.children"
                  :animation="300"
                  class="flex flex-col  p-4 w-100% rounded"
                  ghostClass="ghost"
                  handle=".handle"
                >
                  <div v-for="(item,i) in question.children"
                       :key="item.id"
                       class="item h-35px rounded flex items-center px-4 mb-1"
                       style="width: 100%;position: relative;">
                    <svg-icon class="handle cursor-move" icon-class="drag-and-drop" />
                    <svg-icon v-if="projectQuestionTypeStrategies[question.type]?.icon"
                              class="ml-1" style="width: 1rem"
                              :icon-class="projectQuestionTypeStrategies[question.type]?.icon"
                    />
                    <el-input v-if="projectQuestionTypeStrategies[question.type]?.inputTitle"
                              style="width: 20%" class="ml-2 mr-2"
                              v-model="item.title" type="text" />
                    <el-input
                      :type="projectQuestionTypeStrategies[question.type]?.inputType" class="ml-2 mr-2"
                      :model-value="getDynamicValue(item, question.type)"
                      @update:model-value="val => setDynamicValue(item, question.type, val)"
                      :resize="projectQuestionTypeStrategies[QuestionType.Textarea]?.inputResize"
                    />
                    <!--显示分值-->
                    <div style="width: 100px;">
                          <span
                            v-if="projectQuestionTypeStrategies[question.type]?.showCorrectAnswer?.(question, item)"
                            class="form-answer">(正确答案)</span>
                      <span v-if="projectQuestionTypeStrategies[question.type]?.showScore?.(question, item)"
                            class="form-answer">(分值{{ item.attribute.examScore }})</span>
                    </div>
                    <!--                          题目选项按钮组-->
                    <div class="form-remove">
                      <svg-icon class="cursor-pointer mr-2" icon-class="cancel"
                                @click="remove(<number>index,<number>i)" color="#DC143C"></svg-icon>
                    </div>
                  </div>
                </VueDraggable>
                <div class="mb-4">
                  <a-flex v-show="activeQuestionIndex!==index" gap="small" justify="end">
                    <a-tag
                      v-if="question.tags"
                      v-for="(tag, t) in question.tags"
                      :key="tag" :color="getAntTagColor(t)" class="mr-1">
                      {{ tag }}
                    </a-tag>
                  </a-flex>
                  <div v-if="activeQuestionIndex===index" class="form-select">
                    <el-form>
                      <!--添加选项-->
                      <el-form-item
                        v-if="[QuestionType.Radio,QuestionType.Checkbox,QuestionType.MultipleBlank].includes(question.type)">
                        <el-button round icon="plus" plain type="success" @click="addItem(index)">
                          添加选项
                        </el-button>
                      </el-form-item>
                      <div class="flex ">
                        <el-select
                          v-if="currentTemplate"
                          v-model="currentTemplate.tags"
                          :max-collapse-tags="5" :reserve-keyword="false"
                          allow-create clearable collapse-tags
                          collapse-tags-tooltip filterable multiple
                          placeholder="选择标签" value-key="tagsName" style="width: 100%"
                        >
                          <el-option v-for="item in templateTagList" :key="item.tagId" :label="item.tagName"
                                     :value="item.tagName">
                          </el-option>
                        </el-select>
                      </div>
                    </el-form>
                  </div>
                </div>
              </div>
            </div>
            <div v-if="projectForm.survey.children.length===0 && view==='edit'" class="m-auto"
                 v-html="DragDemonstration">
            </div>
          </VueDraggable>
        </div>
        <div v-if="view==='json'">
          <VueJsonPretty showLineNumber showLength
                         :data="formatToJsonObject(projectForm.survey)" />
        </div>
        <div v-if="view==='preview'">
          <template-preview :project-form="projectForm" />
        </div>
      </a-card>
    </el-main>
  </el-container>
  <el-aside class="sidebar-container drawer-shadow">
    <a-flex justify="center" class="segmented-style mb-2">
      <el-segmented v-model="setting" :options="settingOptions">
        <template #default="scope">
          <svg-icon :icon-class="scope.item['icon']" />
          <span class="ml-1">{{ scope.item['label'] }}</span>
        </template>
      </el-segmented>
    </a-flex>
    <!--全局设置-->
    <div v-if="setting==='base' && projectForm.setting">
      <div class="setting-item">
        <el-text>显示进度条</el-text>
        <el-switch v-model="projectForm.setting.answerSetting.progressBar" />
      </div>
      <div class="setting-item">
        <el-text>一页一题</el-text>
        <el-switch v-model="projectForm.setting.answerSetting.onePageOneQuestion" />
      </div>
    </div>
    <!--          题目配置-->
    <div v-if="isCurrentTemplate &&setting==='template'">
      <div class="setting-item">
        <el-text>切换题型</el-text>
        <el-select v-model="currentTemplate.type" @change="handleSettingType">
          <el-option v-for="item in exam_question_type" :key="item.value" :label="item.label"
                     :value="item.value" />
        </el-select>
      </div>
      <div class="setting-item">
        <el-text>题干说明</el-text>
        <el-switch v-model="showQuestionDescription" @change="handleQuestionDescription()" />
      </div>

      <a-divider>选项</a-divider>
      <!-- 选项布局 -->
      <div class="setting-item">
        <el-text>选项布局
          <el-tooltip content="当前问题的选项排成几列">
            <span><svg-icon icon-class="tip" /></span>
          </el-tooltip>
        </el-text>
        <el-input-number v-model="currentTemplate.attribute.columns" size="small"
                         :min="1" :max="currentTemplate.children.length" />
      </div>
      <!-- 计分方式配置 -->
      <div class="setting-item" style="flex-direction: column;">
        <div>计分方式</div>
        <el-select v-model="currentTemplate.attribute.examAnswerMode"
                   @change="handleSettingAnswerMode()" style="width:100%">
          <el-option
            v-for="mode in projectQuestionTypeStrategies[currentTemplate.type]?.answerModes"
            :key="mode.value" :label="mode.label" :value="mode.value" />
        </el-select>
        <el-select v-if="projectQuestionTypeStrategies[currentTemplate.type]?.['matchRules']"
                   v-model="currentTemplate.attribute.examMatchRule"
                   class="mt-2" style="width:100%">
          <el-option
            v-for="rule in projectQuestionTypeStrategies[currentTemplate.type]?.['matchRules']"
            :key="rule.value" :label="rule.label" :value="rule.value" />
        </el-select>
      </div>

      <div v-if="[ExamAnswerMode.onlyOne,ExamAnswerMode.selectAll].includes(currentTemplate.attribute.examAnswerMode) &&
                          ![QuestionType.FillBlank,QuestionType.MultipleBlank,QuestionType.Textarea].includes(currentTemplate.type)"
           class="setting-item"
           style="flex-direction: column;">
        <div>答案</div>
        <el-select v-model="selectedRadioAnswerId" @change="handleRadioAnswer()" style="width:100%"
                   v-if="currentTemplate.type!==QuestionType.Checkbox">
          <el-option v-for="item in currentTemplate.children" :label="item.title" :value="item.id" />
        </el-select>
        <div v-for="item in currentTemplate.children" v-if="currentTemplate.type===QuestionType.Checkbox"
             :key="item.id"
             class="flex items-center">
          <el-checkbox v-model="item.attribute.examCorrectAnswer" :false-value="null" :true-value="item.id">
            {{ item.title }}
          </el-checkbox>
        </div>
        <div class="setting-item">
          <span>此题分值</span>
          <el-input-number v-model="currentTemplate.attribute.examScore"
                           :precision="1" :step="0.5"
                           size="small" @change="getScoreTotal()" />
        </div>
      </div>
      <div v-if="[ExamAnswerMode.selectCorrect,ExamAnswerMode.select].includes(currentTemplate.attribute.examAnswerMode)&&
                          ![QuestionType.FillBlank,QuestionType.MultipleBlank,QuestionType.Textarea].includes(currentTemplate.type)">
        <div class="setting-item" style="flex-direction: column;">
          <div>各选项分值</div>
          <div v-for="item in currentTemplate.children" class="setting-item" style="font-size: 12px">
            <span>{{ item.title }}</span>
            <el-input-number v-model="item.attribute.examScore"
                             :precision="1" :step="0.5"
                             size="small" @change="handleQuestionMaxScore(item.attribute.examScore)" />
          </div>
        </div>
        <div class="setting-item">
          <el-text>此题分值</el-text>
          <el-input-number v-model="currentTemplate.attribute.examScore"
                           :precision="1" :step="0.5"
                           size="small" @change="getScoreTotal()" />
        </div>
      </div>
      <div v-if="currentTemplate.type===QuestionType.MultipleBlank||currentTemplate.type===QuestionType.FillBlank">
        <div>各选项分值</div>
        <div v-for="item in currentTemplate.children"
             :key="item.id" class="setting-item" style="flex-direction: column;">
          <span>{{ item.title }}</span>
          <el-input v-model="item.attribute.examCorrectAnswer"
                    type="textarea"
                    :autosize="{ minRows: 3, maxRows: 6 }"
                    resize="vertical" />
          <div class="setting-item" v-if="currentTemplate.attribute.examAnswerMode===ExamAnswerMode.select">
            <el-text>此项分值</el-text>
            <el-input-number v-model="item.attribute.examScore"
                             :precision="1" :step="0.5"
                             size="small" @change="handleQuestionMaxScore(item.attribute.examScore)" />
          </div>
        </div>
        <div class="setting-item" v-if="currentTemplate.attribute.examAnswerMode===ExamAnswerMode.selectAll">
          <el-text>此题分值</el-text>
          <el-input-number v-model="currentTemplate.attribute.examScore"
                           :precision="1" :step="0.5"
                           size="small" @change="getScoreTotal()" />
        </div>
      </div>
      <div v-if="currentTemplate.type===QuestionType.Textarea">
        <div>答案</div>
        <div v-for="item in currentTemplate.children"
             :key="item.id" class="setting-item" style="flex-direction: column;">
          <el-input v-model="item.attribute.examCorrectAnswer"
                    type="textarea"
                    :autosize="{ minRows: 3, maxRows: 6 }"
                    resize="vertical" />
        </div>
        <div class="setting-item">
          <el-text>此题分值</el-text>
          <el-input-number v-model="currentTemplate.attribute.examScore"
                           :precision="1" :step="0.5"
                           size="small" @change="getScoreTotal()" />
        </div>
      </div>


      <div class="setting-item" style="flex-direction: column;">
        <span>答案解析</span>
        <el-input v-model="currentTemplate.attribute.examAnalysis"
                  type="textarea"
                  :autosize="{ minRows: 3, maxRows: 6 }"
                  resize="vertical" />
      </div>
    </div>
    <el-collapse accordion v-if="isCurrentTemplate &&setting==='option'">
      <el-collapse-item v-for="item in currentTemplate['children']" :key="item.id" :title="item.title">
        <el-input v-model="item.id">
          <template #append>
            <el-button icon="copyDocument" @click="copyId(item.id)" />
          </template>
        </el-input>
      </el-collapse-item>
    </el-collapse>
  </el-aside>

  <el-dialog v-model="addDialog.visible" width="500px">
    <el-form :rules="addRules" :model="addTemplateForm" label-width="100px">
      <el-form-item label="题目名称" prop="templateName">
        <el-input v-model="addTemplateForm.template.title" />
      </el-form-item>
      <el-form-item label="选择题库" prop="repoId">
        <el-select v-model="addTemplateForm.repoId">
          <el-option v-for="item in repoList" :key="item.repoId" :label="item.repoName" :value="item.repoId" />
        </el-select>
      </el-form-item>
      <el-button round type="primary" plain :loading="addLoading" @click="submitAdd">
        <template #icon>
          <svg-icon icon-class="success" />
        </template>
        确定
      </el-button>
      <el-button round @click="addDialog.visible=false">
        <template #icon>
          <svg-icon icon-class="close" />
        </template>
        取消
      </el-button>

    </el-form>
  </el-dialog>
  <el-dialog v-model="dialog.visible" width="800px">
    <a-alert type="warning" closable class="mb-2">
      <template #description>
        <div>描述您想要生成的试题，形容的越细致，生成的试题越贴近</div>
        <b>例如: </b>我要生成软件工程专业课的题目，涵盖软件工程各知识点，用于教学检验与学习提升，题目形式多样，难度适配不同学习阶段，要求准确、创新且有质量。
      </template>
    </a-alert>
    <div class="total-hint" :style="{ color: totalNum > 30 ? '#ff4d4f' : '#666' }">
      当前总题数：{{ totalNum }}/30
    </div>
    <el-input :disabled="genLoading" type="textarea" v-model="genForm.requirements" resize="none" />
    <a-spin :spinning="genLoading" size="large">
      <el-table :data="genForm.children" height="200px" :show-header="false">
        <el-table-column prop="type" align="center">
          <template #default="scope">
            题型:
            <el-select v-model="scope.row.type" style="width: 150px">
              <el-option v-for="item in exam_question_type" :label="item.label"
                         :value="item.value" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="num" align="center">
          <template #default="scope">
            题目数量:
            <el-input-number
              :min="1"
              :max="getMaxAllowed(scope.row)"
              v-model.number="scope.row.num"
              @change="handleNumChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column width="80px" align="center">
          <template #default="scope">
            <el-tooltip content="移除本行数据">
              <el-button circle plain type="danger" @click="removeGenRow(scope.$index)" icon="delete" />
            </el-tooltip>
          </template>
        </el-table-column>
        <template #empty>
          <a-empty />
        </template>
      </el-table>
    </a-spin>
    <a-button class="mb-2" @click="addGenRow()" type="dashed" style="width: 100%">添加一行数据</a-button>
    <el-button round :loading="genLoading" type="primary" plain @click="submitGen()"
               :disabled="genForm.children.length===0 || genForm.requirements===''||totalNum>30">
      <template #icon>
        <svg-icon icon-class="success" />
      </template>
      提交
    </el-button>
    <el-button :loading="genLoading" round plain @click="resetGen">
      <template #icon>
        <svg-icon icon-class="reset" />
      </template>
      重置
    </el-button>
  </el-dialog>
  <file-import :import-dialog="importDialog" @update:visible="handleDialogClose"
               @update:data="importTemplate" />
</template>

<style lang="scss" scoped>
@import "style";
</style>
